package com.carlinfo.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class FileUtil
{
	Logger logger = LogManager.getLogger();

	public String readFile(File file)
	{
		try
		{
			InputStream is = new FileInputStream(file);
			return this.readFile(is);
		} catch (FileNotFoundException e)
		{
			logger.error("读取文件失败了!", e);
		}
		return "";
	}

	public static void copy(InputStream is, OutputStream os)
	{
		/* 用于拼装路径,因为目标文件不存在 */
		/* 准备管子 */
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		/* 准备容器 */
		byte[] b = new byte[1024 * 1024];
		/* 拼装路径 */
		try
		{

			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(os);

			int len = 0;
			while ((len = bis.read(b)) != -1)
			{
				/* 写数据 */
				bos.write(b, 0, len);
			}
			bos.flush();
		} catch (FileNotFoundException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		} catch (Exception e)
		{
			e.printStackTrace();
		} finally
		{
			try
			{
				if (bis != null)
				{
					/* 记得关闭管子 */
					bis.close();
					bis = null;
				}
			} catch (IOException e)
			{
				e.printStackTrace();
			}
			try
			{
				if (bos != null)
				{
					/* 关闭管子 */
					bos.close();
					bos = null;
				}
			} catch (IOException e)
			{
				e.printStackTrace();
			}
		}
	}

	public String readFile(InputStream is)
	{
		StringBuffer sb = new StringBuffer();
		BufferedReader bfr = null;
		try
		{
			InputStreamReader isr = new InputStreamReader(is);
			bfr = new BufferedReader(isr);
			String line = "";
			while ((line = bfr.readLine()) != null)
			{
				sb.append(line + "\r\n");
			}
			return sb.toString();
		} catch (IOException e)
		{
			logger.error("读取文件内容失败了!", e);
		}
		return "";
	}

	public static void main(String[] args)
	{
		InputStream is = FileUtil.class.getClassLoader().getClass().getResourceAsStream("/dataJson.json");
		FileUtil fileUtil = new FileUtil();
		String str = fileUtil.readFile(is);
		System.out.println(str);
	}

}
